package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApUnlikesBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApUnlikesBehaviorService;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.ApUserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUnlikesBehaviorServiceImpl extends ServiceImpl<ApUnlikesBehaviorMapper, ApUnlikesBehavior> implements ApUnlikesBehaviorService {

    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;

    /**
     * 保存或更新不喜欢行为
     *
     * @return
     */
    @Override
    public ResponseResult unlikesBehavior(UnLikesBehaviorDto dto) {

        //检查参数
        if (null == dto || null == dto.getArticleId()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //查询当前用户
        Integer userId = ApUserThreadLocal.getUserId();
        if (null == userId || userId == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //查询行为实体
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(userId, dto.getEquipmentId());
        if (null == apBehaviorEntry) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //判断数据是否存在
        ApUnlikesBehavior apUnlikesBehavior = getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery()
                .eq(ApUnlikesBehavior::getEntryId, apBehaviorEntry.getId())
                .eq(ApUnlikesBehavior::getArticleId, dto.getArticleId()));
        if (null == apUnlikesBehavior) {

            //没有数据 保存数据
            apUnlikesBehavior = new ApUnlikesBehavior();
            apUnlikesBehavior.setEntryId(apBehaviorEntry.getId());
            apUnlikesBehavior.setArticleId(dto.getArticleId());
            apUnlikesBehavior.setType(Integer.valueOf(dto.getType()));
            apUnlikesBehavior.setCreatedTime(new Date());

            save(apUnlikesBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } else {

            //有数据 修改数据
            apUnlikesBehavior.setType(Integer.valueOf(dto.getType()));

            updateById(apUnlikesBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }
}
